package com.pioneer.fationservice.serviceinfos;

import java.util.HashMap;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pioneer.fationservice.R;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.entries.ShopInfoDetailEntry;
import com.pioneer.fationservice.helpers.PhoneHelper;
import com.pioneer.fationservice.models.ResponseObject;
import com.pioneer.fationservice.models.ShopInfoDetailModel;
import com.pioneer.fationservice.parsers.BaseParser;
import com.pioneer.fationservice.parsers.ShopInfoDetailParser;
import com.pioneer.fationservice.selfctls.BannerView;
import com.pioneer.fationservice.selfctls.BannerView.BannerViewListener;
import com.pioneer.fationservice.selfctls.IndictorView;
import com.pioneer.fationservice.selfctls.ScrollerView;

/**
 * 商家详情
 * @author Mrper
 *
 */
public class ShopDetailActivity extends FinalActivity {
	
	@ViewInject(id=R.id.layout_actionbar_txtTitle) private TextView txtTitle;//标题文本栏
	@ViewInject(id=R.id.activity_shop_detail_imgBack,click="onBackClick") private ImageView imgBack;//返回
	@ViewInject(id=R.id.activity_shop_detail_svScroller) private ScrollerView svScroller;//滑动视图
	@ViewInject(id=R.id.activity_shop_detail_flBvContainer) private FrameLayout flBvContainer;//图片展示框容器
	@ViewInject(id=R.id.activity_shop_detail_bvPics) private BannerView bvPics;//图片展示
	@ViewInject(id=R.id.activity_shop_detail_ivIndictor) private IndictorView ivIndcitor;//指示器
	@ViewInject(id=R.id.activity_shop_detail_txtShopName) private TextView txtShopName;//商家名称
	@ViewInject(id=R.id.activity_shop_detail_txtShopIntroduce) private TextView txtShopIntroduce;//商家介绍
	@ViewInject(id=R.id.activity_shop_detail_txtShopCall) private TextView txtShopCall;//商家电话
	@ViewInject(id=R.id.activity_shop_detail_txtShopCollect,click="onCollectClick") private TextView txtShopCollect;//收藏
	@ViewInject(id=R.id.activity_shop_detail_txtShopShare,click="onShareClick") private TextView txtShopShare;//分享
	@ViewInject(id=R.id.activity_shop_detail_imgShopCall,click="onCallShopClick") private ImageView imgShopCall;//拨打电话
	@ViewInject(id=R.id.activity_shop_detail_txtShopAddr) private TextView txtShopAddr;//商家地址
	@ViewInject(id=R.id.activity_shop_detail_txtViewMap,click="onViewMapClick") private TextView txtViewMap;//查看地图
	@ViewInject(id=R.id.activity_shop_detail_txtShopAlert) private TextView txtShopMeeting;//预约提醒
	@ViewInject(id=R.id.activity_shop_detail_txtShopService) private TextView txtShopService;//商家服务
	@ViewInject(id=R.id.activity_shop_detail_txtShopTime) private TextView txtShopTime;//营业时间
	@ViewInject(id=R.id.activity_shop_detail_txtShopType) private TextView txtShopType;//商家类型
	@ViewInject(id=R.id.activity_shop_detail_txtShopHttp) private TextView txtShopHttp;//官方地址
	@ViewInject(id=R.id.activity_shop_detail_txtShopScore) private TextView txtShopScore;//是否积分
	@ViewInject(id=R.id.activity_shop_detail_txtShopMsg) private TextView txtShopMsg;//温馨提示
	
	private ShopInfoDetailEntry shopInfoDetail;//商家详细信息
	private int flag = 0;//商家类型
	
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_detail);
		txtTitle.setText("商家详情");
		bvPics.setParentView(svScroller);//用于拦截父窗口的事件
		bvPics.setOnBannerViewLister(new BannerViewListener() {
			@Override
			public void selectedChanged(int selection) {
				ivIndcitor.setIndictorSelectedIndex(selection);
			}
			@Override
			public void imageClick(int selection) {
			}
		});
		ivIndcitor.setIndictorCount(bvPics.getImglstSize());
		Intent intent = getIntent();//获取商家详细信息,需要传递flag类型参数
		if(intent!=null && intent.hasExtra("shopId") && intent.hasExtra("flag")){
			flag = intent.getIntExtra("flag", 0);//获取商家类型
			requestShopDetailInfo(intent.getIntExtra("shopId", 0));
		}
	};
	
	/**
	 * 返回操作
	 * @param view
	 */
	public void onBackClick(View view){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
	}
	
	/**
	 * 分享点击
	 * @param v
	 */
	public void onShareClick(View v){
		Toast.makeText(this, "暂未开放此功能!", Toast.LENGTH_SHORT).show();
	}
	
	/**
	 * 收藏的点击事件
	 * @param view
	 */
	public void onCollectClick(View view){
		requestShopCollect(shopInfoDetail.isCollect);//请求收藏信息
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
			imgBack.performClick();//模拟点击返回按钮
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 拨打电话
	 * @param view
	 */
	public void onCallShopClick(View view){
		if(shopInfoDetail == null) return;
		final String phones[] = shopInfoDetail.shopPhone.split("/");
		if(phones.length == 1){
			PhoneHelper.callPhoneNumber(ShopDetailActivity.this, phones[0]);
			return;
		}
		new AlertDialog.Builder(this).setTitle("请选择")
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setItems(phones, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					PhoneHelper.callPhoneNumber(ShopDetailActivity.this, phones[which]);
				}
			})
		.show();
	}
	
	/**
	 * 查看地图
	 * @param view
	 */
	public void onViewMapClick(View view){
		Intent intent = new Intent(this,ServiceMapActivity.class);
		if(shopInfoDetail!=null){
			intent.putExtra("shopId", shopInfoDetail.shopId);
			intent.putExtra("flag", flag);
			intent.putExtra("shopName", shopInfoDetail.shopName);
			intent.putExtra("longtitude", shopInfoDetail.shopLatlng.longitude);
			intent.putExtra("latitude", shopInfoDetail.shopLatlng.latitude);
		}
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
	}
	
	/**
	 * 商家详细信息
	 * @param entry
	 */
	public void setShopDetailInfo(ShopInfoDetailEntry entry){
		if(entry == null) return;
		txtShopName.setText(entry.shopName);
		txtShopAddr.setText(entry.shopAddress);
		txtShopCall.setText("电话："+entry.shopPhone);
		txtShopIntroduce.setText(entry.shopDescription);
		txtShopService.setText(entry.shopServer);
		txtShopScore.setText(entry.shopScore);
		txtShopTime.setText(entry.shopTime);
		txtShopMeeting.setText(entry.shopYuyue);
		txtShopMsg.setText(entry.shopTip);
		txtShopType.setText(flag == 1?"美食":(flag==2?"酒店":(flag==3?"景点":"维修店")));
		txtShopHttp.setText(entry.shopHttp);
		Drawable drawable = getResources().getDrawable(entry.isCollect?R.drawable.ic_shop_favorite:
			R.drawable.ic_shop_unfavorite);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		txtShopCollect.setCompoundDrawables(drawable, null, null, null);
		//装载图片数据
		int length = entry.piclst.size();
		switch(length){
		case 0:
			flBvContainer.setVisibility(View.GONE);
		case 1:
			ivIndcitor.setVisibility(View.GONE);
			break;
		default:
			ivIndcitor.setIndictorCount(length);
			String[] picArr = new String[length];
			entry.piclst.toArray(picArr);
			bvPics.setImageUrls(picArr);
			break;
		}
	}
	
	/**
	 * 请求收藏信息
	 */
	public void requestShopCollect (final boolean isCollect){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "请稍等...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("uid", String.valueOf(SystemData.uid));
    	params.put("sid", String.valueOf(shopInfoDetail.shopId));
    	params.put("f",isCollect?"0":"1");
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_COLLECT, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			Toast.makeText(ShopDetailActivity.this, (isCollect?"收藏失败，请重试！":"取消收藏失败，请重试!"), Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("收藏商家信息（"+isCollect+"）---返回结果："+str);
    			ResponseObject model = (new BaseParser(ResponseObject.class,str){
					@Override
					public void parseJSONModels(Object jsonModels,boolean isJSONObject) {
					}
				}).getResponseObject();
    			if(model.status == 1){
    				Drawable drawable = getResources().getDrawable(isCollect?R.drawable.ic_shop_unfavorite:
						R.drawable.ic_shop_favorite);
    				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    				txtShopCollect.setCompoundDrawables(drawable, null, null, null);
    				shopInfoDetail.isCollect = !isCollect;
    			}
    			Toast.makeText(ShopDetailActivity.this, model.status == 1?(isCollect?"取消收藏成功!":"收藏成功!"):model.msg,
						Toast.LENGTH_SHORT).show();
    		}
    	});
	}
	
	/**
	 * 获取商家详细信息
	 * @param shopId
	 */
	public void requestShopDetailInfo(int shopId){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "请稍等...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("sid", String.valueOf(shopId));
    	params.put("uid", String.valueOf(SystemData.uid));
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_DETAIL_INFO, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			Toast.makeText(ShopDetailActivity.this, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("商家详细信息----返回信息："+str);
    			ShopInfoDetailModel model = new ShopInfoDetailParser(str).getResponseObject();
    			switch(model.status){
    			case 1:
    				shopInfoDetail = model.shopInfoDetail;
    				setShopDetailInfo(shopInfoDetail);//设置商家详细信息
    				break;
    			case 0:
    				Toast.makeText(ShopDetailActivity.this, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
    		}
    	});
	}
}
